package com.jmu.edu.IMApplication.fragment;

import android.os.Bundle;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.material.button.MaterialButton;
import com.jmu.edu.IMApplication.MyApplication;
import com.jmu.edu.IMApplication.R;
import com.jmu.edu.IMApplication.adapter.ContactItemAdapter;
import com.jmu.edu.IMApplication.adapter.SearchFriendItemAdapter;
import com.jmu.edu.IMApplication.event.SwitchFragmentEvent;
import com.jmu.edu.IMApplication.utils.ViewUtils;
import com.jmu.edu.IMApplication.utils.WillowUtils;
import com.wang.avi.AVLoadingIndicatorView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;

import cn.jpush.im.android.api.callback.GetUserInfoCallback;
import cn.jpush.im.android.api.model.UserInfo;


public class SearchFriendFragment extends Fragment {
    private MaterialButton backButton;
    private RecyclerView recyclerView;
    private SearchFriendItemAdapter adapter;
    private EditText searchText;
    private AVLoadingIndicatorView animation;


    public SearchFriendFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        EventBus.getDefault().register(this);
        return inflater.inflate(R.layout.fragment_search_friend, container, false);

    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (hidden) {
            EventBus.getDefault().unregister(this);
        } else {
            EventBus.getDefault().register(this);
            ViewUtils.addBackListenerForHide(getView(), backButton);
        }
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initView();
        ViewUtils.addBackListenerForHide(getView(), backButton);
    }

    @Subscribe
    public void onSwitchFragmentEvent(SwitchFragmentEvent event) {
        // 如果hideTag对上了，那么说明就是这个Fragment要隐藏
        if (event.getHideTag().equals("searchFriend")) {
            ViewUtils.hideFragment(SearchFriendFragment.this, event.getShowFragment(), event.getShowTag(), R.anim.from_right, R.anim.out_left);
        }
    }

    private void initView() {
        backButton = getView().findViewById(R.id.fragment_search_friend_back);
        searchText = getView().findViewById(R.id.fragment_search_friend_searchBar);
        animation = getView().findViewById(R.id.fragment_search_friend_animation);
        animation.hide();
        initListener();
        recyclerView = getView().findViewById(R.id.fragment_search_friend_recyclerView);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
        linearLayoutManager.setOrientation(RecyclerView.VERTICAL);
        recyclerView.setLayoutManager(linearLayoutManager);
        if (adapter == null) {
            adapter = new SearchFriendItemAdapter();
        }


    }

    private void initListener() {
        backButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ViewUtils.hideFragment(SearchFriendFragment.this, R.anim.from_right, R.anim.out_right);
            }
        });
        searchText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {

//                if (actionId == EditorInfo.IME_ACTION_DONE) {
                if (actionId == KeyEvent.ACTION_DOWN || actionId == EditorInfo.IME_ACTION_DONE) {
                    //目前只能执行单个查找，所以先传入一个只有一个数据的列表
//                    Toast.makeText(getContext(), "触发了回车监听", Toast.LENGTH_SHORT).show();
                    loadData();
                    return true;
                }
                return false;
            }
        });
    }

    public void loadData() {
        animation.show();
        // 这个是要进行模糊搜索的username
        String username = searchText.getText().toString();
        WillowUtils.getUserInfo(username, new GetUserInfoCallback() {
            @Override
            public void gotResult(int i, String s, UserInfo userInfo) {
                animation.hide();
                if (userInfo != null) {
                    Log.d("搜索用户界面", "搜索用户数据" + userInfo.getUserName());
                    //获取数据，将数据传入适配器，并提醒recyclerView更新数据
                    List<UserInfo> userInfoList = new ArrayList<>();
                    userInfoList.add(userInfo);
                    adapter.setUserInfoList(userInfoList);
                    //如果recyclerView还没有设置适配器，说明是第一次设置，这个时候是第一次加载，不需要提醒数据发生改变
                    if (recyclerView.getAdapter() == null) {
                        recyclerView.setAdapter(adapter);
                        Log.d("搜索用户界面", "现在是第一次加载");
                    } else {
                        // 如果执行else，说明不是第一次加载数据，这个时候要提醒数据发生改变
                        Log.d("搜索用户界面", "现在不是第一次加载");
                        adapter.notifyDataSetChanged();
                    }

                } else {
                    Log.d("搜索用户界面", "没有搜索到用户" + i + "||" + s);
                    Toast.makeText(getContext(), "没有找到该用户", Toast.LENGTH_SHORT).show();
                    adapter.setUserInfoList(new ArrayList<UserInfo>());
                    adapter.notifyDataSetChanged();
                }
            }
        });
    }
}